﻿var layer, laypage, form, JsonData = {}, EditSingle = 0, base = "./handler/", index = 0, _name = null;;
var namespaces = namespaces || {};
layui.config({
    base: 'plugins/layui/modules/'
});

(function ($) {
    //定义一些默认参数
    var options = {
        'get_url': null,
        'field_idA': '*',
        'field_idB': '*',
        'container': 'effect-6',
        'dialogID':0,
        'row': 0,
        'column': 0,
        'curr': 1,
        'tableA': null,
        'tableB': null,
        'rowCount': 0,
        'pagecount':0,
        'rowNum': 10,
        'select_row': 10,
        'id_selector': function (selector) {
            return document.getElementById(selector);
        }
    }
    //定义一些api
    var plugin_api = {
        init: function (param) {
            if (!param) param = {};
            if (typeof param['get_url'] !== 'undefined') { options.get_url = param['get_url']; }
            if (typeof param['field_idA'] !== 'undefined') { options.field_idA = param['field_idA']; }
            if (typeof param['field_idB'] !== 'undefined') { options.field_idB = param['field_idB']; }
            if (typeof param['container'] !== 'undefined') { options.container = param['container']; }
            if (typeof param['dialogID'] !== 'undefined') { options.dialogID = param['dialogID']; }
            if (typeof param['row'] !== 'undefined') { options.row = param['row']; }
            if (typeof param['column'] !== 'undefined') { options.column = param['column']; }
            if (typeof param['curr'] !== 'undefined') { options.curr = param['curr']; }
            if (typeof param['tableA'] !== 'undefined') { options.tableA = param['tableA']; }
            if (typeof param['tableB'] !== 'undefined') { options.tableB = param['tableB']; }
            if (typeof param['pagecount'] !== 'undefined') { options.pagecount = param['pagecount']; }
            if (typeof param['rowCount'] !== 'undefined') { options.rowCount = param['rowCount']; }
            if (typeof param['rowNum'] !== 'undefined') { options.rowNum = param['rowNum']; }
            if (typeof param['select_row'] !== 'undefined') { options.select_row = param['select_row']; }
            
            plugin_api.GetValue();
        },
        GetValue: function () {
            options.select_row = parseInt($("#select_row").val()) ? parseInt($("#select_row").val()) : options.rowNum;
            var sql1, sql2,sql3;
            if (options.curr == 1) {
                sql1 = "select SQL_CALC_FOUND_ROWS " + options.field_idA + " from " + options.tableA + " order by time DESC" + " limit 0," + options.curr * options.select_row + ";";
                sql2 = "SELECT FOUND_ROWS();";
                sql3 = "select " + options.field_idB + " from " + options.tableB + " order by time DESC";
            }
            else {
                sql1 = "select SQL_CALC_FOUND_ROWS " + options.field_idA + " from " + options.tableA + " order by time DESC" + " limit " + (options.curr - 1) * options.select_row + "," + options.select_row + ";";
                sql2 = "SELECT FOUND_ROWS();";
                sql3 = "select " + options.field_idB + " from " + options.tableB + " order by time DESC";
            }
            $.ajax({
                type: 'POST',
                url: base + options.get_url + ".ashx?t=" + Math.random().toString(),
                data: {
                    "sql1": sql1,
                    "sql2": sql2,
                    "sql3": sql3,
                    //"table": options.table
                    // "curr": options.rowNum
                },
                dataType: 'json',
                cache: false,
                beforeSend: function () {
                    //加载中
                    //options.dialogID = layer.load(1, {
                    //    shade: [0.1, '#fff'] //0.1透明度的白色背景
                    //});
                },
                success: function (data, textStatus) {
                    //parent.layer.msg('加载完毕！', { icon: 1, time: 1000 });
                    //layer.close(options.dialogID)
                    var jsonObj = eval(data);
                    var jsonData;
                    $("#" + options.container).empty();
                    $.each(jsonObj, function (index, item) {
                        switch (index) {
                            case "Record-0":
                                jsonData = eval(item);
                                $.each(jsonData, function (idx, itm) {
                                        $("#" + options.container).append('<div class="img">'+
                                            '<img id="' + itm.id + '" src="' + itm.path + '" onerror="nofind();" alt="">' +
                                            '<div class="overlay">'+
                                            ' <a class="check-overlay" href="#"><img src="plugins/Gallery/img/false.png"></a>'+
                                            '<a class="delete-overlay" href="#"><img src="plugins/Gallery/img/delete.png"></a>'+
                                            ' <a class="edit-overlay" href="#"><img src="plugins/Gallery/img/edit.png"></a>'+
                                            '<a class="link-overlay" href="#"><img src="plugins/Gallery/img/link.png"></a>' +
                                            '</div></div>');
                                })
                                break;
                            case "Record-1":
                                jsonData = eval(item);
                                $.each(jsonData, function (idx, itm) {
                                    //jsd = eval(jsonData[idx]);
                                    //$.each(jsd, function (_idx, _itm) {
                                    //    //console.log(_itm);
                                    //})
                                })
                                break;
                            case "PageCount":
                                console.log(item); break;
                            default: break;
                        }
                    })
                   
                    $(function () {
                        var lis = $('.img'),
                            container = $("#effect-6 div"),
                            index = 0,
                            btnck = $('#checkAll'),
                            mask = $('.mask'),
                            close = $(".close"),
                            btnl = $(".btnl"),
                            btnr = $(".btnr");
                        if (Modernizr.touch) {
                            // show the close overlay button
                            //$(".close-overlay").removeClass("hidden");
                            // handle the adding of hover class when clicked
                            $(".img").click(function (e) {
                                if (!$(this).hasClass("hover")) {
                                    $(this).addClass("hover");
                                }
                            });
                            // handle the closing of the overlay
                            $(".close-overlay").click(function (e) {;
                                e.preventDefault();
                                e.stopPropagation();
                                if ($(this).closest(".img").hasClass("hover")) {
                                    $(this).closest(".img").removeClass("hover");
                                }
                            });
                        } else {
                            // handle the mouseenter functionality
                            $(".img").mouseenter(function () {
                                $(this).addClass("hover");
                            })
                            // handle the mouseleave functionality
                            .mouseleave(function () {
                                $(this).removeClass("hover");
                            });
                            $(".check-overlay").click(function (e) {
                                console.log($(this) + "--checkbox操作");
                                var str = $(this).children().prop("src");
                                var index = str.lastIndexOf("\/");
                                str = str.substring(index + 1, str.length);
                                str == "true.png" ? ($(this).children().prop("src", "plugins/Gallery/img/false.png"), $(this).parent().parent().removeClass("select")) : ($(this).children().prop("src", "plugins/Gallery/img/true.png"), $(this).parent().parent().addClass("select"));
                                e.preventDefault();
                                e.stopPropagation();
                                if ($(this).closest(".img").hasClass("hover")) {
                                    $(this).closest(".img").removeClass("hover");
                                }
                            });
                            $(".delete-overlay").click(function (e) {
                                console.log($(this) + "--删除操作");
                                e.preventDefault();
                                e.stopPropagation();
                                if ($(this).closest(".img").hasClass("hover")) {
                                    $(this).closest(".img").removeClass("hover");
                                }
                            });
                            $(".edit-overlay").click(function (e) {
                                console.log($(this) + "--编辑操作");
                                e.preventDefault();
                                e.stopPropagation();
                                if ($(this).closest(".img").hasClass("hover")) {
                                    $(this).closest(".img").removeClass("hover");
                                }
                            });
                            $(".link-overlay").click(function (e) {
                                console.log($(this) + "--复制链接操作");
                                e.preventDefault();
                                e.stopPropagation();
                                if ($(this).closest(".img").hasClass("hover")) {
                                    $(this).closest(".img").removeClass("hover");
                                }
                            });
                            $(".img").click(function (e) {
                                mask.show();
                                console.log($(this) + "--预览操作操作");
                                mask.find('img').prop('src', $(this).find("img").attr('src'));
                                index = $(this).index();
                                if (!$(this).hasClass("hover")) {
                                    $(this).addClass("hover");
                                }
                            });
                        }

                        mask.hide();
                        lis.on('click', function () {
                            var imgP = $(this).find('img').prop('src');
                            mask.show();
                            mask.find('img').prop('src', imgP);
                            index = $(this).index();

                        })
                        close.on('click', function () {
                            mask.hide();
                        })

                        btnr.on('click', function () {
                            index++;
                            if (index == lis.length) {
                                index = 0;
                            }
                            console.log(index);
                            var imgP = lis.eq(index).find('img').prop('src');
                            $('img', mask).fadeOut(300).prop('src', imgP).fadeIn(300);
                        })

                        btnl.on('click', function () {
                            index--;
                            if (index < 0) {
                                index = lis.length - 1;
                            }
                            var imgP = lis.eq(index).find('img').prop('src');
                            $('img', mask).fadeOut(300).prop('src', imgP).fadeIn(300);
                        })

                        $(document).on('dbclick', mask, function () {
                            /*var obj=e.target;
                            $(!$(obj).is('img')&&!$(obj).is('btnl')&&!$(obj).is('btnr')&&!$(obj).is('obj'))*/
                            mask.hide()
                        })
                        function CheckAll() {
                            //console.log($("#effect-6").children());

                        }
                        btnck.on('click', function () {
                            container.siblings("div.img").each(function () {
                                $(this).hasClass("select") ? ($(this).removeClass("select"), $(this).children().children().children(":first").prop("src", "plugins/Gallery/img/false.png")) : ($(this).addClass("select"), $(this).children().children().children(":first").prop("src", "plugins/Gallery/img/true.png"));
                            });
                        });

                    })

                },
                error: function (xhr) {
                    if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) { // 兼容调试时301/302重定向导致触发error的问题
                        //console.log(xhr);
                        this.success(eval('(' + xhr.responseText + ')'), xhr.statusText);
                    }
                    //parent.layer.msg('加载失败', { icon: 2, time: 1000 });
                },
            });
        }
    }
    //这里确定了插件的名称
    this.CJPlugin = plugin_api;
})(jQuery)

//批量上传插件
//KindEditor.ready(function (K) {
//    var d = new Date();
//    var t = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes();
//    var classname = "未分类";
//    editor = K.editor({
//        uploadJson: './kindeditor/upload_json.ashx?Custom_directory=' + classname + '&t=' + t,
//        fileManagerJson: './kindeditor/file_manager_json.ashx',
//    });
//    K('#upload').click(function () {
//        editor.loadPlugin('multiimage', function () {
//            editor.plugin.multiImageDialog({
//                clickFn: function (urlList) {
//                    var div = K('#ImgUl');
//                    var count = $("#ImgUl").find("li").length;
//                    K.each(urlList, function (i, data) {
//                        div.append('<li id="li-' + Number(i + count) + '"><a id="a-' + Number(i + count) + '" href="' + data.url + '" data-rel="colorbox" class="cboxElement" style="background:url(img/empty.png) no-repeat center;-webkit-transition:1s all linear; background-size:contain;">'
//                              + '<img id="img-' + Number(i + count) + '" width="160" height="160" alt="160x160" src="' + data.url + '" onerror=javascript:this.src="img/empty.png";></a>'
//                              + '<div class="tools tools-bottom in"><a href="#"><i class="ace-icon fa fa-link"></i></a>'
//                              + '<a href="#"><i class="ace-icon fa fa-paperclip"></i></a>'
//                              + '<a href="#"><i class="ace-icon fa fa-pencil"></i></a>'
//                              + '<a href="#"><i class="ace-icon fa fa-times red"></i></a>'
//                              + '<input type="checkbox" id="check"></div></li>');
//                    });
//                    editor.hideDialog();
//                    Init_Gallery();
//                }
//            });
//        });
//    });
//});
////选择分类后重新初始化图片上传插件
//function load() {
//    KindEditor.ready(function (K) {
//        var d = new Date();
//        var t = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes();
//        var classname = $("#img_class option:selected").text() == "选择分类" ? "选择分类" : $("#img_class option:selected").text();
//        editor = K.editor({
//            uploadJson: './kindeditor/upload_json.ashx?Custom_directory=' + classname + '&t=' + t,
//            fileManagerJson: './kindeditor/file_manager_json.ashx',
//        });
//    });
//}


function delrow(id, img_url, li, table, key) {
    var sqlstring = "delete from " + table + " where " + key + "='" + id + "';"
    var index;
    //询问框
    layer.confirm('您是否要删除？', {
        btn: ['是的', '算了'] //按钮
    }, function () {
        if (execute(sqlstring)) {
            return $.ajax({                                                  //调用jquery的ajax方法   
                type: "POST",                                      //设置ajax方法提交数据的形式   
                url: "handler/ExecuteFile.ashx?Imgurl=" + img_url,                                       //把数据提交到ashx  
                beforeSend: function () {
                    index = layer.load(2, { shade: [0.2, '#393D49'] });
                },
                success: function (msg) {                  //提交成功后的回调，msg变量是输出的内容。      
                    //如果有必要，可以把msg变量的值显示到某个DIV元素中 
                    layer.close(index)
                    layer.msg('处理成功', { icon: 1, time: 2000 });
                    $("#" + li).remove();
                    return true;
                },
                error: function (xhr) {
                    if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) { // 兼容调试时301/302重定向导致触发error的问题
                        console.log(xhr);
                        this.success(eval('(' + xhr.responseText + ')'), xhr.statusText);
                        index.close();
                        return false;
                    }
                    //layer.msg('处理失败', { icon: 2, time: 2000 });
                    return false;
                },
            });
        }
    }, function () {
        //layer.msg('取消', {
        //    time: 20000, //20s后自动关闭
        //    btn: ['明白了', '知道了']
        //});
    });
}



function changeURL(imgID) {
    var Imgurl = $("#" + imgID).attr("src");
    var regA = new RegExp("[^\x00-\xff]*[^\x00-\xff]");
    var classname = Imgurl.match(regA);
    var url = window.location.host;
    window.history.pushState({}, 0, 'http://' + url + window.location.pathname + '#' + classname);
}
function Init_Kindeditor(btn_id, index) {
    KindEditor.ready(function (K) {
        editor = K.editor({
            uploadJson: './kindeditor/upload_json.ashx',
            allowFileManager: false,
        });
        $('#' + btn_id).click(function () {
            editor.loadPlugin('image', function () {
                editor.plugin.imageDialog({
                    showRemote: false,
                    //imageUrl: K('#' + img_id).val(),
                    clickFn: function (url, title, width, height, border, align) {
                        Single_Pic_Insert(btn_id, $("#select-class option:selected").text(), url);
                        $('#a-' + index).attr("href", url);
                        $('#img-' + index).attr("src", url);
                        $('#copy-' + index).attr("data-clipboard-text", url);
                        editor.hideDialog();
                    }
                });
            });
            var Img_url = $('#img-' + index).attr("src");
            var reg = new RegExp("(?=\/image\/).*(?=\/*\/)");
            var str = Img_url.substr(1).match(reg);
            var classname = str[0].substr(7);
            var url = $("#action_form").attr("action");
            var value = $.GetQueryString.Get(url, "Custom_directory");
            url = url.replace(value, classname);
            $("#action_form").attr("action", url);
        });
    });
}

function Single_Pic_Insert(id, _classname, _imageurl) {
    var classid = uuid(6, 16);
    var reg = new RegExp(".*(?=\/image\/).*(?=\/*\/).?");
    var str = _imageurl.substr(1).match(reg);
    var filename = _imageurl.substring(str[0].length + 1);
    var d = new Date();
    var t = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes();
    if (_classname != "选择分类") {
        var sqlstring = "UPDATE gallery SET classname='" + _classname + "', path='" + _imageurl + "' WHERE id='" + id + "'";
    } else {
        var sqlstring = "UPDATE gallery SET path='" + _imageurl + "' WHERE id='" + id + "'";
    }
    $.ajax({                                                  //调用jquery的ajax方法   
        type: "POST",                                      //设置ajax方法提交数据的形式   
        url: "handler/ExecuteHandler.ashx",                                       //把数据提交到ashx  
        data: "sql=" + sqlstring,     //输入框writer中的值作为提交的数据 
        beforeSend: function () {

        },
        success: function (msg) {                  //提交成功后的回调，msg变量是输出的内容。      
            //如果有必要，可以把msg变量的值显示到某个DIV元素中 
            //layer.msg('处理成功', { icon: 1, time: 2000 });
            return true;
        },
        error: function (xhr) {
            if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) { // 兼容调试时301/302重定向导致触发error的问题
                this.success(eval('(' + xhr.responseText + ')'), xhr.statusText);
                return false;
            }
            //layer.msg('处理失败', { icon: 2, time: 2000 });
            return false;
        },
    });
}


//刷新按钮
function Refreshbtn() {
    var Array_id = new Array("id", "classname", "filename", "path", "time");
    page("handler/PageHandler.ashx?t=", "handler/GetHandler.ashx?t=", Array_id, "main", '20', 'gallery');
}
//添加分类
function Addclass() {
    var index = layer.open({
        type: 2,
        scrollbar: false,
        shade: [0.2, '#FFFFFF'],
        title: "添加分类",
        shadeClose: false,
        area: ['400px', '170px'],
        content: '/master/add-gallery-class.html',
    });
}
//删除按钮
function Delbtn() {
    deleteAll('gallery');
}


//分类管理
function Classbtn() {
    //分类管理
    var index = layer.open({
        type: 2,
        shade: [0.2, '#393D49'],
        scrollbar: false,
        title: '分类管理',
        content: '/master/gallery-class-manage.html',
        area: ['1000px', '600px'],
    });

}

//图片上传
function Pic_Insert(data) {
    var values = null;
    var jsonData = eval(data);
    $.each(jsonData, function (index, objVal) {
        var classname = $("#img_class option:selected").text() == "选择分类" ? "选择分类" : $("#img_class option:selected").text();
        if ($("#img_class option:selected").text() == "选择分类") {
            //var regA = new RegExp("(?=\/image\/).*(?=\/*\/)");
            var regA = new RegExp("[^\x00-\xff]*[^\x00-\xff]");
            var classname = objVal.match(regA);
            var regB = new RegExp(".*(?=\/image\/).*(?=\/*\/).?");
            var strB = objVal.substr(1).match(regB);
            var filename = objVal.substring(strB[0].length + 1);
        }
        else {
            var regB = new RegExp(".*(?=\/image\/).*(?=\/*\/).?");
            var strB = objVal.substr(1).match(regB);
            var filename = objVal.substring(strB[0].length + 1);
        }
        var classid = uuid(6, 16);
        var d = new Date();
        var t = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes();
        if (index == 0) {
            values = "('" + classid + "','" + classname + "','" + filename + "','" + objVal + "','" + t + "')";
        } else {

            values += ",('" + classid + "','" + classname + "','" + filename + "','" + objVal + "','" + t + "')";
        }
    });
    var sqlstring = "insert into gallery (id, classname , filename, path , time) values " + values;
    $.ajax({                                                  //调用jquery的ajax方法   
        type: "POST",                                      //设置ajax方法提交数据的形式   
        url: "handler/ExecuteHandler.ashx",                                       //把数据提交到ashx  
        data: "sql=" + sqlstring,     //输入框writer中的值作为提交的数据 
        beforeSend: function () {

        },
        success: function (msg) {                  //提交成功后的回调，msg变量是输出的内容。      
            //如果有必要，可以把msg变量的值显示到某个DIV元素中 
            //layer.msg('处理成功', { icon: 1, time: 2000 });
            JsonData = {};
            return true;
        },
        error: function (xhr) {
            if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) { // 兼容调试时301/302重定向导致触发error的问题
                this.success(eval('(' + xhr.responseText + ')'), xhr.statusText);
                return false;
            }
            //layer.msg('处理失败', { icon: 2, time: 2000 });
            return false;
        },
    });
}

//添加分类
function createFolder(get_url, classname) {
    var d = new Date();
    var t = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes();
    var id=uuid(6, 16);
    $.ajax({
        type: 'get',
        url: get_url,
        data: "classname=" + classname + "&id=" + id + "&time=" + t,
        dataType: 'text',
        cache: false,
        beforeSend: function () {
            dialogID = layer.load(2, { shade: [0.1, '#fff'] });
        },
        success: function (data, textStatus) {
            layer.close(dialogID);
            layer.msg('添加成功', { icon: 1, time: 2000 });
        },
        error: function (xhr) {
            if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) { // 兼容调试时301/302重定向导致触发error的问题
                console.log(xhr);
                this.success(eval('(' + xhr.responseText + ')'), xhr.statusText);
                return;
            }
            layer.close(dialogID);
            layer.msg('加载失败', { icon: 1, time: 2000 });
            return;
        },

    });
}



